<?php
namespace Common\Services;

use Common\Models\UserModel;
use Common\Models\UserAchievementModel;

class UserAchievementService {
  public function findFirst($user_id) {
    $findFirstUserAchievement = UserAchievementModel::findFirst($user_id);
    if(!$findFirstUserAchievement) {
      return $this -> create([
        'user_id' => $user_id,
        'day_amount_left' => 0,
        'day_amount_right' => 0,
        'month_amount_left' => 0,
        'month_amount_right' => 0
      ]);
    }

    return ['code' => 0, 'user_achievement' => $findFirstUserAchievement];
  }

  public function create($data) {
    $userAchievementModel = new UserAchievementModel($data);
    try {
      if(!$userAchievementModel -> create()) {
        $messages = $userAchievementModel -> getMessages();
        throw new \Exception($messages[0] -> getMessage());
      }
    } catch(\Exception $e) {
      return ['code' => -1, 'message' => $e -> getMessage()];
    }

    return ['code' => 0, 'user_achievement' => $userAchievementModel];
  }
}
?>